package com.bardsoftware.foronuvolo.client;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.tools.zip.AsiExtraField;

import com.bardsoftware.foronuvolo.data.DiscussionTag;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.UListElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HTMLTable;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class DiscussionMessageSender extends MessageSender {
	//private final TagServiceAsync myTagService = GWT.create(TagService.class);
	private final Button createNewTagButton ;
	private final TextBox newTagNameField;
	//private final ListBox listBoxTags = new ListBox(true);
	//private final AbsolutePanel tagCheckBoxPanel = new AbsolutePanel();
	//UListElement uListElement = Document.get().createULElement();
	private final VerticalPanel tagCheckBoxPanel = new VerticalPanel();

	public DiscussionMessageSender(
			RootPanel textAreaPanel,
			RootPanel sendButtonPanel, 
			RootPanel panelForTags,
			final StartDiscussionServiceAsync startDiscService, 
			final TagServiceAsync tagService,
			final String outputElementID,
			final String errorElementID) {
		super(textAreaPanel, sendButtonPanel, startDiscService, outputElementID, errorElementID);
		
		newTagNameField = new TextBox();
    	newTagNameField.setFocus(true);
    	//newTagNameField.setWidth("100%");
    	
    	createNewTagButton = new Button("CreateTag");
    	//createNewTagButton.addStyleName("CreateTag");
    	createNewTagButton.setStylePrimaryName("gp-button");
    	//myNewTagPanel.setSize("100%", "100%");
       	
    	tagService.getAllTagsName(
    			new AsyncCallback<List<String>>() {
    				public void onFailure(Throwable caught) {
    					DiscussionMessageSender.this.onFailure(caught);
    				}
    				
    				public void onSuccess(List<String> result) {
    					//DiscussionMessageSender.this.onSuccessGetAllTags(result);
    					for (String tagName : result) {
    						//listBoxTags.addItem(tagName);
							tagCheckBoxPanel.add(new CheckBox(tagName));
						}
    				}
    			});
    	
    	HorizontalPanel createNewTagPanel = new HorizontalPanel();
    	createNewTagPanel.add(newTagNameField);
    	createNewTagPanel.add(createNewTagButton);
    	VerticalPanel commonPanel = new VerticalPanel();
    	commonPanel.add(tagCheckBoxPanel);
    	commonPanel.add(createNewTagPanel);
    	panelForTags.add(commonPanel);
    	
        class MyHandler implements ClickHandler, KeyUpHandler {
            public void onClick(ClickEvent event) {
                sendNewTagNameToServer();
            }
            public void onKeyUp(KeyUpEvent event) {
                if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER && event.isControlKeyDown()) {
                    sendNewTagNameToServer();
                }
            }
            private void sendNewTagNameToServer() {
                createNewTagButton.setEnabled(false);
                String tagNameToServer = newTagNameField.getText();
                tagService.addTagName(
                        tagNameToServer,
                        new AsyncCallback<String>() {
                            public void onFailure(Throwable caught) {
                                DiscussionMessageSender.this.onFailure(caught);
                            }
                            public void onSuccess(String result) {
                                DiscussionMessageSender.this.onSuccessAddTag(result);
                            }
                        });
            }
        }
        // Add a handler to send the name to the server
        MyHandler handler = new MyHandler();
        
        createNewTagButton.addClickHandler(handler);
        newTagNameField.addKeyUpHandler(handler); 
	}

	protected void onSuccessAddTag(String result) {
		//listBoxTags.addItem(result);
		if(result!=null&&!result.equals("")){
			CheckBox newCheckBox = new CheckBox(result);
			newCheckBox.setChecked(true);
			tagCheckBoxPanel.add(newCheckBox);
			newTagNameField.setText("");
		}
		createNewTagButton.setEnabled(true);
	}
	
	protected void addSendHandler(final MessageSendService startDiscService) {
		addStartDiscHandler((StartDiscussionServiceAsync) startDiscService);
	}
	
	private void addStartDiscHandler(final StartDiscussionServiceAsync startDiscService) {
		class SendHandler implements ClickHandler, KeyUpHandler {
			public void onClick(ClickEvent event) {
				sendTextToServer();
			}
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER && event.isControlKeyDown()) {
					sendTextToServer();
				}
			}
			private void sendTextToServer() {
				sendButton.setEnabled(false);
				//createNewTagButton.setEnabled(false);
				String textToServer = messageField.getText();
				startDiscService.startDiscussion(
						textToServer,
						getTags(),
						new AsyncCallback<String>() {
							public void onFailure(Throwable caught) {
								DiscussionMessageSender.this.onFailure(caught);
							}
							public void onSuccess(String result) {
								DiscussionMessageSender.this.onSuccess(result);
							}
						});
			}
			private List<String> getTags() {
				List<String> res = new ArrayList<String>();				
				for (Widget checkBox : tagCheckBoxPanel) {
					if(((CheckBox)checkBox).isChecked()){
						res.add(((CheckBox)checkBox).getText());
					}
				}
				return res;
			}
		}
		
		// Add a handler to send the name to the server
		SendHandler handler = new SendHandler();
		
		//createNewTagButton.addClickHandler(handler);
		sendButton.addClickHandler(handler);
		messageField.addKeyUpHandler(handler);
	}

}
